//index.js
const app = getApp()

Page({
  data: {
    //选择的词库
    choiceCikuFlag: null,
    //模式，顺序还是随机
    mode: null,
    //等级
    level: null,
    //顺序的话，当前进度多少条，总词库进度条数
    cikuOrder: 0,
    //随机的话，当前进度是多少条
    cikuRandom: 0,
    //当前拉取的单词
    charmword: null,
    //图片列表集合
    beautyList: null,
    
    //配置有没有变动,默认变动了
    settingChange: true,

    //当前单词的提示信息
    showWord: '',
    //输入单词
    inputWord: '',
    //当前单词
    word: '',
    //音频播放组件
    innerAudioContext: null,

    isFocus: false,
    //透明度
    opactity: 1,

    imageShow: false
  },

  openKeyboard: function () {
    this.setData({
      isFocus: true,
      selectionStart: this.data.inputWord.length,
      selectionStart: this.data.inputWord.length
    })
  },

  /**
   * 监听键盘输入
   */
  listenKeyInput: function (e) {
    var that = this;
    var text = e.detail.value;
    if(text.length > that.data.word.length){
      text = text.substr(0, that.data.word.length);
    }
    that.setData({
      inputWord: text
    })
    //实时对比展示
    that.checkWord();
    //检查，如果单词全对了，就展示图片，并下一个单词
    if(that.upperCase(that.data.inputWord) == that.upperCase(that.data.word)){
      //判断单词是否已全背完
      if(that.data.mode == 'order' && that.data.cikuOrder == that.data.choiceCikuFlag.num - 1){
        //说明此本单词已背完，给个提示
        wx.showModal({
          content: "【" + that.data.choiceCikuFlag.name + "】背完了",
          confirmText: "我真厉害",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('弹框后点确定')
            } else {
              console.log('弹框后点取消')
            }
          },
          fail: function (res) {
            console.log('弹框失败');
          }
        })
        that.setBeautyKu();
        return;
      }
      //全对了
      console.log("单词全对了！");
      that.setBeautyKu();
      that.isStudyOrLazy();
      that.setData({
        inputWord: ''
      })
      that.checkWord();
    }
  },

  onFocus: function (e) {
    var that = this;
    that.setData({ isFocus: true });
  },

  // setValue: function (e) {
  //   var that = this;
  //   console.log("value:"+e.detail.value);
  //   that.setData({ inputWord: e.detail.value });
  //   //实时对比展示
  //   that.checkWord();
  //   //检查，如果单词全对了，就展示图片，并下一个单词
  //   console.log(that.upperCase(that.data.inputWord));
  //   console.log(that.upperCase(that.data.word));
  //   console.log(that.upperCase(that.data.inputWord) == that.upperCase(that.data.word));
  //   if(that.upperCase(that.data.inputWord) == that.upperCase(that.data.word)){
  //     //判断单词是否已全背完
  //     if(that.data.mode == 'order' && that.data.cikuOrder == that.data.choiceCikuFlag.num - 1){
  //       //说明此本单词已背完，给个提示
  //       wx.showModal({
  //         content: "【" + that.data.choiceCikuFlag.name + "】背完了",
  //         confirmText: "我真厉害",
  //         showCancel: false,
  //         success: function (res) {
  //           if (res.confirm) {
  //             console.log('弹框后点确定')
  //           } else {
  //             console.log('弹框后点取消')
  //           }
  //         },
  //         fail: function (res) {
  //           console.log('弹框失败');
  //         }
  //       })
  //       that.setBeautyKu();
  //       return;
  //     }
  //     //全对了
  //     console.log("单词全对了！");
  //     that.setBeautyKu();
  //     that.isStudyOrLazy();
  //   }
  // },

  //设置缓存的图库信息
  setBeautyKu() {
    var that = this;
    var idx = that.data.mode == 'order' ? that.data.cikuOrder % 20 : that.data.cikuRandom;
    wx.previewImage({
      urls: [that.data.beautyList[idx].link]
    });
    //设置缓存图片
    var beautyImgArr = wx.getStorageSync('beautyList');
    if(beautyImgArr == null || beautyImgArr.length <= 0){
      beautyImgArr = new Array();
    }
    if(beautyImgArr.length >= 20){
      //删除旧的一个数组
      that.remove(beautyImgArr, 0);
    }
    beautyImgArr.push(that.data.beautyList[idx].link)
    wx.setStorageSync('beautyList', beautyImgArr)
  },

  // 删除方法
  remove: function(array,idx){
    for (var i = 0; i < array.length; i++) {
      if (i == idx){
        array.splice(i, 1);
      }
    }
    return -1; 
  },

  //这个单词背完了，或者不想背，跳过去了
  isStudyOrLazy: function() {
    var that = this;
    if(that.data.mode == 'order'){
      that.setData({
        cikuOrder: that.data.cikuOrder + 1
      })
      var cikuFlag = that.data.choiceCikuFlag.flag;
      wx.setStorageSync('ciku-order-cache-'+cikuFlag, that.data.cikuOrder);
      if(that.data.cikuOrder % 20 == 0){
        //这一批20个背完了，刷新下一批
        that.getCharmwordListOrder();
        that.getBeautyList();
      }else{
        that.checkWord();
      }
    }else{
      that.setData({
        cikuRandom: that.data.cikuRandom + 1
      })
      if(that.data.cikuRandom % 20 == 0){
        //这一批背完了，拉取下一批
        that.getCharmwordListRandom();
        that.getBeautyList();
      }else{
        that.checkWord();
      }
    }
    //刷新页面元素
    //清空输入的单词
    that.setData({
      inputWord: '',
      isFocus: true
    })
    wx.hideKeyboard()
  },

  upperCase: function(value) {
    return value.toString().toUpperCase();
  },

  //显示的提示单词随着输入单词变化而变化
  checkWord: function() {
    var that = this;
    var word = that.getThisWord();
    //每对一个字母，透明度加多少，总透明度0.6
    var oneOpactity = 0.6 / word.length;
    var opactity = 1;
    console.log("当前单词:" + word + ",对一个单词字母的透明度："+oneOpactity);
    var strBuf = '';
    for(var i = 0; i < word.length; i ++){
      if(i == 0){
        strBuf = word[i];
      }else if(i == word.length -1){
        strBuf = strBuf + word[i];
      }else{
        if(that.data.inputWord.length > i && that.upperCase(that.data.inputWord[i]) == that.upperCase(word[i])){
          strBuf = strBuf + ' ' + word[i] + ' ';
        }else{
          strBuf = strBuf + ' _ ';
        }
      }
      //设置透明度
      if(that.data.inputWord.length > i && that.upperCase(that.data.inputWord[i]) == that.upperCase(word[i])){
        //这个字母对了
        opactity = opactity - oneOpactity
      }
    }
    //为了解决单词切换时候，背景图闪现的问题
    var isImageShow = opactity < 1 ? true : false;
    that.setData({
      showWord: strBuf,
      opactity: opactity,
      imageShow: isImageShow
    })
  },

  getThisWord: function() {
    var that = this;
    console.log("that.data.cikuOrder%20="+that.data.cikuOrder%20);
    var trueWord = that.data.mode == 'order' ? that.data.charmword[that.data.cikuOrder%20].word : that.data.charmword[that.data.cikuRandom].word;
    console.log("当前单词是："+trueWord)
    that.setData({
      word: trueWord
    })
    return trueWord;
  },

  playAudio: function() {
    var that = this;
    that.innerAudioContext = wx.getBackgroundAudioManager();
    this.innerAudioContext.title = '单词发音';
    that.innerAudioContext.autoplay = true;
    that.innerAudioContext.src = 'http://dict.youdao.com/dictvoice?audio='+this.getThisWord();
    that.innerAudioContext.onPlay(() => {
        //这里可以写音乐开始播放后的回掉函数
        console.log("音频开始播放了")
    })
    that.innerAudioContext.onError((res) => { 
      // 音频出现播放错误时候的回调函数
      console.log("音频播放失败")
    })

  },

  onShow: function(){
    var that = this;
    //更新设置信息
    that.getSetting();
    //单词为空或者设置变动时候
    if(that.data.charmword == null || that.data.settingChange){
      if(that.data.mode == 'random'){
        that.getCharmwordListRandom();
      }
      if(that.data.mode == 'order'){
        that.getCharmwordListOrder();
      }
      that.getBeautyList();
      wx.setStorageSync('settingChangeCache', false);
      that.setData({
        settingChange: false
      })
    }
  },

  getSetting: function() {
    //先拉取设置，如果设置没有的话，设定个默认值
    //词库设置
    //检查一下是否有选择课程，如果没有选课，默认最简单的初一上课程
    var that = this;
    var choiceCikuCache = wx.getStorageSync('choice-ciku-cache');
    if(choiceCikuCache == null || choiceCikuCache == ''){
      wx.setStorageSync('choice-ciku-cache', JSON.parse('{"flag":"70","name":"初中人教版七年级上","num":224}'));
      that.setData({
        choiceCikuFlag: JSON.parse('{"flag":"70","name":"初中人教版七年级上","num":224}')
      })
    }else{
      that.setData({
        choiceCikuFlag: choiceCikuCache
      })
    }
    console.log("当前词库选择flag:"+ that.data.choiceCikuFlag.name)
    //词库顺序记录
    var cikuFlag = that.data.choiceCikuFlag.flag;
    var cikuOrderCache = wx.getStorageSync('ciku-order-cache-'+cikuFlag);
    if(cikuOrderCache == null || cikuOrderCache == ''){
      wx.setStorageSync('ciku-order-cache-'+cikuFlag, 0);
      that.setData({
        cikuOrder: 0
      })
      wx.setStorageSync('ciku-order-cache-'+cikuFlag, 0);
    }else{
      that.setData({
        cikuOrder: cikuOrderCache
      })
    }
    console.log("当前词库进度:" + that.data.cikuOrder)
    //难度设置
    var mode = wx.getStorageSync('mode');
    if(mode == null || mode == ''){
      this.setData({
        mode: "random"
      })
      wx.setStorageSync('mode', "random");
    }else{
      this.setData({
        mode: mode
      })
    }
    console.log("当前难度:"+ that.data.mode)
    //顺序设置
    var level = wx.getStorageSync('level');
    if(level == null || level == ''){
      this.setData({
        level: "low"
      })
      wx.setStorageSync('level', "low");
    }else{
      this.setData({
        level: level
      })
    }
    console.log("当前顺序:"+ that.data.level)
    var settingChangeCache = wx.getStorageSync('settingChangeCache');
    if(settingChangeCache == null){
      this.setData({
        settingChange: true
      })
      wx.setStorageSync('settingChangeCache', true);
    }else{
      this.setData({
        settingChange: settingChangeCache
      })
      wx.setStorageSync('settingChangeCache', settingChangeCache);
    }
    console.log("当前配置是否有变动:"+ that.data.settingChange)
  },

  onLoad: function() {
    // var that = this;
    // that.getSetting();
    wx.showShareMenu({  
      withShareTicket: true,  
      menus: ['shareAppMessage', 'shareTimeline']  
    })
    // that.getCharmwordListOrder();
    // that.getBeautyList();
  },

  onShareAppMessage(res) {
    if(res.from === "button"){
      //来自页面内的转发按钮
      console.log("来自页面内的转发按钮");
    }else if(res.from === "menu"){
      //来自右上角菜单的转发按钮
      console.log("来自右上角菜单的转发按钮");
    }
    return {
      title: "背单词，看妹子",
      imageUrl: "../../images/resources/share.png",
      path: "/pages/index/index"
    }  
  },

  onShareTimeline() {
    const version = wx.getSystemInfoSync().SDKVersion;
    if (compareVersion(version, '2.11.3') >= 0) {
      return {
        title: "背单词，看妹子",
        imageUrl: "../../images/resources/share.png"
      }
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '微信版本过低，请升级后重试。'
      })
    }
  },

  resetCikuOrder: function() {
    //重置当前词库进度
    var that = this;
    wx.showModal({
      // title: '',
      content: "重置进度?",
      confirmColor: "#01AAED",
      success: function (res) {
        if (res.confirm) {
          wx.setStorageSync('ciku-order-cache-'+that.data.choiceCikuFlag.flag, 0);
          that.setData({
            cikuOrder: 0
          })
          if(that.data.mode == 'order'){
            that.getCharmwordListOrder();
          }
        } else {
          console.log('弹框后点取消')
        }
      },
      fail: function (res) {
        console.log('弹框失败');
      }
    })
  },

  getBeautyList: function() {
    var that = this;
    wx.cloud.callFunction({
      name: "beautyList",
      success: function(res) {
        console.log("图片列表：" + res.result.list)
        that.setData({
          beautyList: res.result.list,
          cikuRandom: 0
        })        
      }
    })
  },

  getCharmwordListOrder: function() {
    console.log("顺序拉取单词")
    var that = this;
    var pageIndex = parseInt(that.data.cikuOrder/20) + 1;
    var type = that.data.choiceCikuFlag.flag * 1;
    console.log("pageindex:{pageIndex},type:{type}", pageIndex, type)
    wx.cloud.callFunction({
      name: "charmwordListOrder",
      data: {
        pageIndex: pageIndex,
        type: type
      },
      success: function(res) {
        console.log("顺序单词获取成功：" + res.result.data)
        that.setData({
          charmword: res.result.data
        })
        that.checkWord();
      }
    })
  },

  getCharmwordListRandom: function() {
    console.log("随机拉取单词")
    var that = this;
    wx.cloud.callFunction({
      name: "charmwordListRandom",
      data: {
        type: that.data.choiceCikuFlag.flag * 1
      },
      success: function(res) {
        console.log("随机单词获取成功：" + res.result.list)
        that.setData({
          charmword: res.result.list,
          cikuRandom: 0
        })
        that.checkWord();
      }
    })
  },

  compareVersion: function(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)
  
    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }
  
    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])
  
      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }
  
    return 0
  },

  toSetting: function() {
    wx.navigateTo({
      url: '../setting/setting'
    })
  },

  //单词提示
  tips: function() {
    var that = this;
    var word = that.data.mode == 'order' ? that.data.charmword[that.data.cikuOrder%20].word : that.data.charmword[that.data.cikuRandom].word;
    var inputWord = that.data.inputWord;
    var idx = 0;
    if(inputWord == null || inputWord == ''){
      idx = 1;
    }else{
      if(inputWord.length + 1 >= word.length){
        wx.showModal({
          content: "只能提示这么多~",
          confirmText: "知道了",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('弹框后点确定')
            } else {
              console.log('弹框后点取消')
            }
          },
          fail: function (res) {
            console.log('弹框失败');
          }
        })
        return;
      }else{
        idx = inputWord.length + 1;
      }
    }
    wx.showToast({
      title: that.upperCase(word.substring(inputWord.length, idx)),
      duration: 1500,
      icon: "none"
    });
  },

  //下个单词
  next: function() {
    var that = this;
    //判断单词是否已全背完
    if(that.data.mode == 'order' && that.data.cikuOrder == that.data.choiceCikuFlag.num - 1){
      //说明此本单词已背完，给个提示
      wx.showModal({
        content: "没有单词了~",
        confirmText: "知道了",
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            console.log('弹框后点确定')
          } else {
            console.log('弹框后点取消')
          }
        },
        fail: function (res) {
          console.log('弹框失败');
        }
      })
      return;
    }
    that.isStudyOrLazy();
  }
  
})
